#include "displaythread.h"
#include "parsedatathread.h"

extern int CollectType;  // 1:连续采集;2:触发采集
extern int Frequency;
extern int TimeLength;
extern int VoltageLevel;
extern bool IsCollect;
extern QString CurrentPath;
extern QVector<QString> DataDates;
extern int TriggerMode;
extern QMutex MuteDisp;
extern QMutex MuteSave;
extern QMutex MuteParse;

DisplayThread::DisplayThread(QObject *parent) : QObject(parent)
{
    for(int i = 0; i < CHANNELCOUNT; i++)
        MaxValue[i] = 0;
    IsTrigged = false;
    IsSaving = false;
    NoiseTest = false;
    FreqTimeLen = Frequency * TimeLength;
    connect(&RcvTimer, SIGNAL(timeout()), this, SLOT(RcvTimeout()));
}

void DisplayThread::SampeleWaveCount(QVector<double> *SrcData)
{
    FreqTimeLen = Frequency * TimeLength;
//    qDebug() << "shift start: " << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
    QVector<double> data[CHANNELCOUNT];
    if(SrcData[0].size() > 0) {
        QMutexLocker loker(&MuteParse);
        for(int i = 0; i < CHANNELCOUNT; i++) {
            data[i] = SrcData[i];
            DisplayData[i].clear();
            MaxValue[i] = 0;
            NoiseValue[i] = 0;
        }
    }
    if(RcvTimer.isActive())
        RcvTimer.stop();
    RcvTimer.start(3000);
//    qDebug() << "shift mid: " << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
    if(DataBuf[0].size() <= 0)
        SaveTime = ParseDataThread::GetCurrentDateTime();
    for(int j = 0; j < data[0].size(); j++) {
        for(int i = 0; i < CHANNELCOUNT; i++) {
            if(NoiseTest) {
                NoiseValue[i] = NoiseValue[i] / (j + 1) * j + fabs(data[i].at(j)) / (j + 1);
                continue;
            }
            if(j % GetSampCnt(Frequency) == 0) {
                if(fabs(data[i].at(j)) > fabs(MaxValue[i]))
                    MaxValue[i] = fabs(data[i].at(j));
                DisplayData[i].push_back(data[i].at(j));
            }
            if(CollectType == 2) { // 触发采集
                if(fabs(data[i].at(j)) >= VoltageLevel) {
                    if(!IsTrigged) {
                        SaveTime = ParseDataThread::GetCurrentDateTime();
                        emit TrigDataTip();
                    }
                    IsTrigged = true;
                }
            }
            else { // 连续采集
                DataBuf[i].push_back(data[i].at(j));
            }
        }
        if(NoiseTest)
            continue;
        if(CollectType == 2) {
            for(int k = 0; k < CHANNELCOUNT; k++) {
                if(IsTrigged) {
                    if(DataBuf[k].size() < 500) {
                        int DifSize = 500 - DataBuf[k].size();
                        for(int x = 0; x < DifSize; x++) {
                            DataBuf[k].push_front(0);
                        }
                    }
                    if(DataBuf[k].size() < Frequency * TimeLength)
                        DataBuf[k].push_back(data[k].at(j));
                }
                else {
                    if(DataBuf[k].size() <= 500) {
                        DataBuf[k].push_back(data[k].at(j));
                    }
                    else if(DataBuf[k].size() > 500) {
                        DataBuf[k].pop_front();
                        DataBuf[k].push_back(data[k].at(j));
                    }
                }
            }
        }
        // 判断队列是否达到存文件条件，满足条件后发送出去数据进行保存
        QMutexLocker loker(&MuteSave);
        if(DataBuf[0].size() == FreqTimeLen) {
            IsTrigged = false;
            for(int k = 0; k < CHANNELCOUNT; k++) {
                SaveBuf[k].clear();
                SaveBuf[k] = DataBuf[k];
                DataBuf[k].clear();
            }
            IsSaving = false;
        }
        // save data
        if(!IsSaving) {
            if(SaveBuf[0].size() == FreqTimeLen) {
                emit SendSaveData(SaveTime, SaveBuf);
                IsTrigged = false;
                IsSaving = true;
            }
        }
    }
    if(NoiseTest) {
        emit SendNoistTestData(NoiseValue);
        NoiseTest = false;
        return;
    }
    QMutexLocker loker(&MuteDisp);
    if(DisplayData[0].size() == 250) {
        for(int k = 0; k < CHANNELCOUNT; k++) {
            MaxValue[k] = GetRangeValue(MaxValue[k]);
        }
        emit SendWaveData(DisplayData, MaxValue);
    }
//    qDebug() << "shift end: " << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
}

void DisplayThread::RcvTimeout()
{
    QString Path = "/mnt/Sync";
    QDir dir(Path);
    if(TriggerMode == 13) {
        // 同步采集模式下，如果出现断数据情况下重新命名Sync文件名
        if(dir.exists()) {
            QFile::rename("/mnt/Sync", "/mnt/Sync_" +
                  QDateTime::currentDateTime().toString("yyyyMMddhhmmss"));
        }
    }
    for(int i = 0; i < CHANNELCOUNT; i++) {
        DataBuf[i].clear();
    }
}

void DisplayThread::NoiseTestSignal()
{
    NoiseTest = true;
}

int DisplayThread::GetRangeValue(float Value)
{
    if(Value < 1)
        return 1;
    else if(Value > 1 && Value <= 10)
        return (int)Value + 3;
    else if(Value > 10 && Value <= 100)
            return Value / 10 + 30;
    else if(Value > 100 && Value <= 1000)
            return Value / 100 + 300;
    else if(Value > 1000 && Value <= 10000)
            return Value / 1000 + 1500;
    else
        return 10000;
}

int DisplayThread::GetChMaxValue(QVector<double> data)
{
    double Value = 0;
    for(int i = 0; i < data.size(); i++) {
        double tmpv = fabs(data.at(i));
        if(Value < tmpv)
            Value = tmpv;
    }
    if(Value < 1)
        return 1;
    else if(Value > 1 && Value <= 10)
        return (int)Value + 1;
    else if(Value > 10 && Value <= 100)
            return Value / 10 + 50;
    else if(Value > 100 && Value <= 1000)
            return Value / 100 + 400;
    else if(Value > 1000 && Value <= 10000)
            return Value / 1000 + 1100;
    else
        return 10000;
}

int DisplayThread::GetSampCnt(int Freq)
{
    switch (Freq) {
    case 500:
        return 2;
    case 1000:
        return 4;
    case 2000:
        return 8;
    case 4000:
        return 16;
    case 8000:
        return 32;
    default:
        return 4;
    }
}
